package com.aliptori.fontinstaller.Logic

import android.Manifest
import android.app.Activity
import android.content.pm.PackageManager
import android.os.Environment
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import com.aliptori.fontinstaller.Logic.POKO.FontMeta
import com.aliptori.fontinstaller.R
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.yurqi.dialog.messageDialog
import java.io.File

/**
 * Created by yeganaaa on 3/30/18.
 */

class LocalFontManager(val activity: Activity, val permissionRequestMessage: (okay: Boolean) -> Unit = {
    if (!it) {
        activity.apply {
            messageDialog(activity, title = getString(R.string.please_grand_readwrite_permission))
        }
    }
}) {

    companion object {
        val fontLocalID = "FontLocalID"
    }

    val readable: Int get() = ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE)
    val writable: Int get() = ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)

    val canReadableWritable: Boolean
        get() {
            val result = readable == PackageManager.PERMISSION_GRANTED && writable == PackageManager.PERMISSION_GRANTED
            if (!result) {
                ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE), 124)
            }

            return result
        }

    private var homePath = "/MIUI/theme/.data"
    private val fontMetaPath: String get() = "$homePath/meta/fonts"
    private val fontContentPath: String get() = "$homePath/content/fonts"
    private val previewPicturesPath: String get() = "$homePath/preview/theme"

    init {
        this.homePath = "${Environment.getExternalStorageDirectory().absolutePath}/$homePath"
        canReadableWritable
    }

    private val gson: Gson by lazy { GsonBuilder().create() }
    val localFonts: Array<FontMeta> by lazy {
        val fonts = ArrayList<FontMeta>()

        permissionRequestMessage(canReadableWritable)

        File(fontMetaPath).list()?.forEach {
            val jsonString = File("$fontMetaPath/$it").readText()

            fonts.add(gson.fromJson(jsonString, FontMeta::class.java))
        }

        fonts.toTypedArray()
    }

    fun getFont(name: String) : FontMeta {
        permissionRequestMessage(canReadableWritable)
        return gson.fromJson(File("$fontMetaPath/$name").readText(), FontMeta::class.java)
    }

    fun replaceNewFont(oldFont: FontMeta, fontFilePath: String) : Exception? {
        var result: Exception? = null


        try {

            val oldFile = "$fontContentPath/${oldFont.localId}.mrc"
            val newFile = fontFilePath

            File(newFile).copyTo(File(oldFile), true)
        }
        catch (excep: Exception){
            result = excep
        }

        return result
    }

}
